package com.insight.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqiao.insight.acore.depart.entity.SysDepart;
import com.yuanqiao.insight.common.constant.CommonConstant;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.constant.CacheConstant;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.util.JwtUtil;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.DateUtils;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.DeptVo;
import com.insight.modules.system.entity.SysDepartRoom;
import com.insight.modules.system.entity.SysUsers;
import com.insight.modules.system.model.DepartIdModel;
import com.insight.modules.system.model.SysDepartTreeModel;
import com.insight.modules.system.service.ISysDepartRoomService;
import com.insight.modules.system.service.ISysDepartService;
import com.insight.modules.system.service.ISysUserDepartService;
import com.insight.modules.system.service.ISysUserService;
import com.insight.modules.umpPwdManage.entity.UmpPwdManage;
import com.insight.modules.umpPwdManage.service.IUmpPwdManageService;
import com.insight.modules.util.ZipEncryUtils;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.*;

/**
 * <p>
 * 部门表 前端控制器
 * <p>
 *
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/sys/sysDepart")
@Slf4j
public class SysDepartController {

	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysUserDepartService sysUserDepartService;
	@Autowired
	private IUmpPwdManageService umpPwdManageService;
	@Autowired
	private ISysDepartRoomService sysDepartRoomService;

	@Autowired
	private ZipEncryUtils zipEncryUtils;

//	@Value("${excel.departPath}")
//	private String path;

	/**
	 * 异步查询部门list
	 * @param parentId 父节点 异步加载时传递
	 * @param ids 前端回显是传递
	 * @return
	 */
	@RequestMapping(value = "/queryDepartTreeSync", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryDepartTreeSync(@RequestParam(name = "pid", required = false) String parentId,@RequestParam(name = "ids", required = false) String ids) {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			List<SysDepartTreeModel> list = sysDepartService != null ? sysDepartService.queryTreeListByPid(parentId, ids) : null;
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 查询数据 查出我的部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryMyDeptTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryMyDeptTreeList() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try {
			if (user != null && oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2)) {
				List<SysDepartTreeModel> list = sysDepartService != null ? sysDepartService.queryMyDeptTreeList(user.getDepartIds()) : null;
				result.setResult(list);
				result.setMessage(CommonConstant.USER_IDENTITY_2.toString());
				result.setSuccess(true);
			} else {
				result.setMessage(CommonConstant.USER_IDENTITY_1.toString());
				result.setSuccess(true);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	@RequestMapping(value="getUserDepType",method = RequestMethod.GET)
    public Result<String> getUserDepType() {
	    String isShow = "N";
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> departs = sysDepartService.getSysDepartByOrgCode(user.getOrgCode());
        if(null != departs && 0 < departs.size()){
            for (SysDepart sysDepart:departs) {
                if("5".equals(sysDepart.getOrgCategory())){
                    isShow = "Y";
                }
            }
        }
	    return Result.OK(isShow);
    }
    /**
     * 沈阳 获取 运维供应商 4
     * @return
     */
    @RequestMapping(value = "/getDepList", method = RequestMethod.GET)
    public Result<List<SysDepart>> getDepList(){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> list = sysDepartService.getDepLists(user);
	    return Result.OK(list);
    }
    /**
     * 沈阳 获取 运维供应商 4
     * @return
     */
    @RequestMapping(value = "/outDepList", method = RequestMethod.GET)
    public Result<List<Map<String,String>>> outDepList(){
        List<SysDepart> list = sysDepartService.getDepLists(null);
        List<Map<String,String>> mapList = new ArrayList<>();
        Map<String,String> map = null;
        for (SysDepart sysDepart : list) {
            map = new HashMap<>();
            map.put("label",sysDepart.getOrgCode());
            map.put("value",sysDepart.getDepartName());
            mapList.add(map);
        }
        return Result.OK(mapList);
    }

    @AutoLog(value = "部门-分页列表查询")
    @ApiOperation(value="部门-分页列表查询", notes="部门-分页列表查询")
    @GetMapping(value = "/outListPage")
    public Result<?> queryPageList(SysDepart sysDepart,
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   HttpServletRequest req) {

        Result<IPage<SysDepart>> result = new Result();

        QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(sysDepart.getDepartName())){
            queryWrapper.like("depart_name",sysDepart.getDepartName());
        }
        if(StringUtils.isNotEmpty(sysDepart.getOrgCode())){
            queryWrapper.like("org_code",sysDepart.getOrgCode());
        }
        queryWrapper.eq("org_category","4");
        queryWrapper.orderByDesc("create_time");
        Page<SysDepart> page = new Page(pageNo, pageSize);
        IPage<SysDepart> pageList = sysDepartService.page(page, queryWrapper);

        IPage<Map<String,String>> mapIpage = new Page<>();
        mapIpage.setTotal(pageList.getTotal());
        mapIpage.setSize(pageList.getSize());
        mapIpage.setCurrent(pageList.getCurrent());
        mapIpage.setPages(mapIpage.getPages());


        List<Map<String,String>> mapList = new ArrayList<>();
        //获取 值班人姓名、班次名称
        if(null != pageList.getRecords() && pageList.getRecords().size()>0) {

            //将额外字段插入到原表基本数据
            pageList.getRecords().forEach(item ->{
                Map<String,String> map = map = new HashMap<>();
                map.put("id",item.getId());
                map.put("departName",item.getDepartName());
                map.put("orgCode",item.getOrgCode());
                map.put("createTime", DateUtils.formatDate(item.getCreateTime()));
                mapList.add(map);
            });
        }
        mapIpage.setRecords(mapList);
        result.setSuccess(true);
        result.setResult(mapIpage);
        return result;
    }

    @RequestMapping(value = "/outAdd", method = RequestMethod.POST)
    @CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public Result<String> outAdd(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		Result<String> result = new Result<String>();
		try {
			if (sysDepart == null) {
				return result.error500("请求参数为空");
			}
			sysDepart.setCreateBy("申报平台");
			sysDepart.setOrgCategory("4");
			sysDepart.setParentId("8c431109337940bbb170ad20328c5be8");
			Result<?> result1 = sysDepartService.saveDepartData(sysDepart, "申报平台");
			if (!result1.isSuccess()) {
				return result.error500("操作失败");
			}
			//添加部门人员
			sysUserService.addUserByDepart(sysDepart);
			result.setResult(sysDepart.getOrgCode());

			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

    public void addUser(SysDepart sysDepart){


    }

    @RequestMapping(value = "/outAddList", method = RequestMethod.POST)
    @CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public Result<String> outAddList(@RequestBody List<Map<String,String>> mapList, HttpServletRequest request) {
		Result<String> result = new Result<String>();
		try {
			if (mapList == null) {
				return result.error500("请求参数为空");
			}
			for (Map<String,String> map : mapList) {
				if (map == null) {
					continue;
				}
				SysDepart sysDepart = new SysDepart();
				sysDepart.setDepartName(map.get("departName"));
				sysDepart.setCode(map.get("code"));
				sysDepart.setCreateBy("申报平台");
				sysDepart.setOrgCategory("4");
				sysDepart.setParentId("8c431109337940bbb170ad20328c5be8");
				if (sysDepartService != null) {
					Result<?> result1 = sysDepartService.saveDepartData(sysDepart, "申报平台");
					if (!result1.isSuccess()) {
						return result.error500("操作失败");
					}
				}
			}
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

    /**
     * 编辑数据 编辑部门的部分数据,并保存到数据库
     *
     * @param sysDepart
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/outAdit", method = RequestMethod.PUT)
    @CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE,CacheConstant.SYS_DICT_TABLE_CACHE}, allEntries=true)
    public Result<?> outAdit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {

        sysDepart.setUpdateBy("申报平台");
		return sysDepartService.updateDepartDataById(sysDepart, "申报平台");
    }
	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@AutoLog(value = "部门管理-部门展示")
	@RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryTreeList() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
			// 从内存中读取
//			List<SysDepartTreeModel> list =FindsDepartsChildrenUtil.getSysDepartTreeList();
//			if (CollectionUtils.isEmpty(list)) {
//				list = sysDepartService.queryTreeList();
//			}
			List<SysDepartTreeModel> list = sysDepartService != null ? sysDepartService.queryTreeList() : null;
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}
	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryTreePowerList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryTreePowerList() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		try {
//            //获取当前登录人//获取当前登录用户信息
//            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//            List<SysDepartTreeModel> list = sysDepartService.queryTreeList(sysUser);

			/*上面两行会根据登录用户获取部门信息,下面这个是获取所有的部门*/
			List<SysDepartTreeModel> list = sysDepartService != null ? sysDepartService.queryTreeList() : null;

            result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
	 *
	 * @param sysDepart
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@AutoLog(value = "部门管理-添加")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public Result<?> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		String username = JwtUtil.getUserNameByToken(request);
		sysDepart.setCreateBy(username);

		// 保存部门数据
		Result<?> result = sysDepartService.saveDepartData(sysDepart, username);
		// 如果部门保存成功，处理房间授权
		if (result.isSuccess() && sysDepart.getRoomIds() != null) {
			/*String[] roomIds = sysDepart.getRoomIds().split(",");*/
			for (String roomId : sysDepart.getRoomIds()) {
				SysDepartRoom sysDepartRoom = new SysDepartRoom();
				sysDepartRoom.setDepartId(sysDepart.getId());
				sysDepartRoom.setRoomId(roomId);
				sysDepartRoom.setOperateDate(new Date());
				sysDepartRoomService.save(sysDepartRoom);
			}


		}

		return result;
	}

	/**
	 * 编辑数据 编辑部门的部分数据,并保存到数据库
	 *
	 * @param sysDepart
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@AutoLog(value = "部门管理-编辑")
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	@Transactional
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE,CacheConstant.SYS_DICT_TABLE_CACHE}, allEntries=true)
	public Result<?> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		String username = JwtUtil.getUserNameByToken(request);
		sysDepart.setUpdateBy(username);
		sysDepartRoomService.remove(new QueryWrapper<SysDepartRoom>().eq("depart_id", sysDepart.getId()));

		// 重新添加新的房间授权
		if (sysDepart.getRoomIds() != null) {
			//String[] roomIds = sysDepart.getRoomIds().split(",");
			for (String roomId : sysDepart.getRoomIds()) {
				SysDepartRoom sysDepartRoom = new SysDepartRoom();
				sysDepartRoom.setDepartId(sysDepart.getId());
				sysDepartRoom.setRoomId(roomId);
				sysDepartRoom.setOperateDate(new Date());
				sysDepartRoomService.save(sysDepartRoom);
			}
		}
		return sysDepartService.updateDepartDataById(sysDepart, username);
	}

	 /**
     *   通过id删除
    * @param id
    * @return
    */
	//@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE,CacheConstant.SYS_DICT_TABLE_CACHE}, allEntries=true)
   public Result<SysDepart> delete(@RequestParam(name="id",required=true) String id) {

       Result<SysDepart> result = new Result<SysDepart>();
       SysDepart sysDepart = sysDepartService.getById(id);
       if(sysDepart==null) {
           result.error500("未找到对应实体");
       }else {
           boolean ok = sysDepartService.delete(id);
           if(ok) {
	            //清除部门树内存
	   		   //FindsDepartsChildrenUtil.clearSysDepartTreeList();
	   		   // FindsDepartsChildrenUtil.clearDepartIdModel();
               result.success("删除成功!");
           }
       }
       return result;
   }


	/**
	 * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
	 *
	 * @param ids
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@AutoLog(value = "部门管理-删除")
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE,CacheConstant.SYS_DICT_TABLE_CACHE}, allEntries=true)
	public Result<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

		Result<SysDepart> result = new Result<SysDepart>();
		if (ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
	public Result<List<DepartIdModel>> queryIdTree() {
//		Result<List<DepartIdModel>> result = new Result<List<DepartIdModel>>();
//		List<DepartIdModel> idList;
//		try {
//			idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//			if (idList != null && idList.size() > 0) {
//				result.setResult(idList);
//				result.setSuccess(true);
//			} else {
//				sysDepartService.queryTreeList();
//				idList = FindsDepartsChildrenUtil.wrapDepartIdModel();
//				result.setResult(idList);
//				result.setSuccess(true);
//			}
//			return result;
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.setSuccess(false);
//			return result;
//		}
		Result<List<DepartIdModel>> result = new Result<>();
		try {
			List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList();
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * <p>
	 * 部门搜索功能方法,根据关键字模糊搜索相关部门
	 * </p>
	 *
	 * @param keyWord
	 * @return
	 */
	@AutoLog(value = "部门管理-查询")
	@RequestMapping(value = "/searchBy", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord,@RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
		Result<List<SysDepartTreeModel>> result = new Result<List<SysDepartTreeModel>>();
		//部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departIds = null;
		if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
			departIds = user.getDepartIds();
		}
		List<SysDepartTreeModel> treeList = this.sysDepartService.searhBy(keyWord,myDeptSearch,departIds);
		if (treeList == null || treeList.size() == 0) {
			result.setSuccess(false);
			result.setMessage("未查询匹配数据！");
			return result;
		}
		result.setResult(treeList);
		return result;
	}


	/**
     * 导出excel
     *
     * @param request
     */
	@AutoLog(value = "部门管理-导出")
    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) {
//        // Step.1 组装查询条件
//        QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
//        //Step.2 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        List<SysDepart> pageList = sysDepartService.list(queryWrapper);
//        //按字典排序
//        Collections.sort(pageList, new Comparator<SysDepart>() {
//            @Override
//			public int compare(SysDepart arg0, SysDepart arg1) {
//            	return arg0.getOrgCode().compareTo(arg1.getOrgCode());
//            }
//        });
//        //导出文件名称
//        mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
//        mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:"+user.getRealname(), "导出信息"));
//        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
//        return mv;
//    }
	public void exportXls(SysDepart sysDepart,HttpServletRequest request,HttpServletResponse response) {
		// Step.1 组装查询条件
		QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
		//Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<SysDepart> pageList = sysDepartService.list(queryWrapper);
		pageList.forEach(item ->{
			if (StringUtils.isNotBlank(item.getParentId())){

				SysDepart depart = sysDepartService.getById(item.getParentId());
				item.setParentId(depart.getDepartName());
			}
		});
		//按字典排序
		Collections.sort(pageList, new Comparator<SysDepart>() {
			@Override
			public int compare(SysDepart arg0, SysDepart arg1) {
				return arg0.getOrgCode().compareTo(arg1.getOrgCode());
			}
		});
		UmpPwdManage zip = umpPwdManageService.getZip();
		zipEncryUtils.zipPwd(response, SysDepart.class,"部门列表",zip.getZipPwd(),zip.getIsEncry(),pageList);
	}

//
//
//	@GetMapping(value = "/downloadTemplate")
//	@ApiOperation("模板导出")
//	public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
//		try {
//			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
//			String str1=path.substring(0, path.indexOf("."));
//			String str2=path.substring(str1.length());
//			ExcelUtil.downloadPoi(inputStream,response,"部门模板"+str2);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
//
//
//
	@AutoLog(value = "部门管理-导入")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@Transactional
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			return sysDepartService.importSheets(file);
		}
		return Result.error("文件导入失败！");
	}
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresRoles({"admin"})
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//		List<String> errorMessageList = new ArrayList<>();
//		List<SysDepart> listSysDeparts = null;
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            MultipartFile file = entity.getValue();// 获取上传文件对象
//            ImportParams params = new ImportParams();
//            params.setTitleRows(2);
//            params.setHeadRows(1);
//            params.setNeedSave(true);
//            try {
//            	// orgCode编码长度
//            	int codeLength = 3;
//                listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
//                //按长度排序
//                Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
//                    @Override
//					public int compare(SysDepart arg0, SysDepart arg1) {
//                    	return arg0.getOrgCode().length() - arg1.getOrgCode().length();
//                    }
//                });
//
//                int num = 0;
//                for (SysDepart sysDepart : listSysDeparts) {
//                	String orgCode = sysDepart.getOrgCode();
//                	if(orgCode.length() > codeLength) {
//                		String parentCode = orgCode.substring(0, orgCode.length()-codeLength);
//                		QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
//                		queryWrapper.eq("org_code", parentCode);
//                		try {
//                		SysDepart parentDept = sysDepartService.getOne(queryWrapper);
//                		if(!parentDept.equals(null)) {
//							sysDepart.setParentId(parentDept.getId());
//						} else {
//							sysDepart.setParentId("");
//						}
//                		}catch (Exception e) {
//                			//没有查找到parentDept
//                		}
//                	}else{
//                		sysDepart.setParentId("");
//					}
//					sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
//					ImportExcelUtil.importDateSaveOne(sysDepart, ISysDepartService.class, errorMessageList, num, CommonConstant.SQL_INDEX_UNIQ_DEPART_ORG_CODE);
//					num++;
//                }
//				//清空部门缓存
//				Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
//				Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
//				redisTemplate.delete(keys3);
//				redisTemplate.delete(keys4);
//				return ImportExcelUtil.imporReturnRes(errorMessageList.size(), listSysDeparts.size() - errorMessageList.size(), errorMessageList);
//            } catch (Exception e) {
//                log.error(e.getMessage(),e);
//                return Result.error("文件导入失败:"+e.getMessage());
//            } finally {
//                try {
//                    file.getInputStream().close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return Result.error("文件导入失败！");
//    }


	/**
	 * 查询所有部门信息
	 * @return
	 */
	@GetMapping("listAll")
	public Result<List<SysDepart>> listAll(@RequestParam(name = "id", required = false) String id) {
		Result<List<SysDepart>> result = new Result<>();
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
		query.orderByAsc(SysDepart::getOrgCode);
		if(oConvertUtils.isNotEmpty(id)){
			String arr[] = id.split(",");
			query.in(SysDepart::getId,arr);
		}
		List<SysDepart> ls = this.sysDepartService.list(query);
		result.setSuccess(true);
		result.setResult(ls);
		return result;
	}
	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryTreeByKeyWord", method = RequestMethod.GET)
	public Result<Map<String,Object>> queryTreeByKeyWord(@RequestParam(name = "keyWord", required = false) String keyWord) {
		Result<Map<String,Object>> result = new Result<>();
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			List<SysDepartTreeModel> list = sysDepartService != null ? sysDepartService.queryTreeByKeyWord(keyWord) : null;
			LambdaQueryWrapper<SysUsers> queryUser = new LambdaQueryWrapper<SysUsers>();
			queryUser.eq(SysUsers::getDelFlag, CommonConstant.DEL_FLAG_0);
			queryUser.and(i -> i.like(SysUsers::getUsername, keyWord).or().like(SysUsers::getRealname, keyWord));
			List<SysUsers> sysUsers = sysUserService != null ? this.sysUserService.list(queryUser) : null;
			map.put("userList", sysUsers);
			map.put("departList", list);
			result.setResult(map);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 根据部门编码获取部门信息
	 *
	 * @param orgCode
	 * @return
	 */
	@GetMapping("/getDepartName")
	public Result<SysDepart> getDepartName(@RequestParam(name = "orgCode") String orgCode) {
		Result<SysDepart> result = new Result<>();
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
		query.eq(SysDepart::getOrgCode, orgCode);
		SysDepart sysDepart = sysDepartService.getOne(query);
		result.setSuccess(true);
		result.setResult(sysDepart);
		return result;
	}

	/**
	 * 根据部门id获取用户信息
	 *
	 * @param id
	 * @return
	 */
	@GetMapping("/getUsersByDepartId")
	public Result<List<SysUsers>> getUsersByDepartId(@RequestParam(name = "id") String id) {
		Result<List<SysUsers>> result = new Result<>();
		List<SysUsers> sysUsers = sysUserDepartService.queryUserByDepId(id);
		result.setSuccess(true);
		result.setResult(sysUsers);
		return result;
	}


	LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();
//	@Value("${deviceStatis.cityId}")
	private String id ;
	/**
	 * 数据迁移测试接口
	 */
	@GetMapping("/testMove")
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	public String testMove() {
		id = cacheUtils.getValueByKey(CommonConstant.DATA_DICT_KEY + "project_cityId_id") + "";
		return sysDepartService.testMove(id);
	}

	@GetMapping(value = "/queryAllTree")
	public List<DeptVo> queryAllTree() {
		List<DeptVo> depts = getDepts(null);
		return depts;
	}

	public List<DeptVo> getDepts(String deptId){
		List<SysDepart> depts =null;
		if (null == deptId){
			depts = sysDepartService.list(new QueryWrapper<SysDepart>().isNull("parent_id").or().eq("parent_id",""));
		}else {
			depts = sysDepartService.list(new QueryWrapper<SysDepart>().eq("parent_id", deptId));
		}
		ArrayList<DeptVo> deptVos = new ArrayList<>();
		if (null != depts){
			for (SysDepart momgDept : depts) {
				DeptVo deptVo1 = new DeptVo();
				deptVo1.setDeptId(momgDept.getId());
				deptVo1.setDeptName(momgDept.getDepartName());
				deptVo1.setCityId(momgDept.getCityId());
				List<DeptVo> depts1 = getDepts(momgDept.getId());
				deptVo1.setChildren(depts1);
				deptVos.add(deptVo1);
			}

		}else {

		}
		return deptVos;
	}

	/**
	 * 查询全部单位
	 *
	 * @return
	 */
	//@AutoLog(value = "单位管理-查询全部单位")
	@ApiOperation(value = "终端组织机构-通过id查询", notes = "终端组织机构-通过id查询")
	@GetMapping(value = "/queryAllDepts")
	public Result<?> queryAll() {
		List<SysDepart> momgDepts = sysDepartService.list(new QueryWrapper<SysDepart>().ne("depart_name", "全部单位"));
		if (momgDepts == null || momgDepts.isEmpty()) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(momgDepts);
	}

	    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
//    @AutoLog(value = "终端组织机构-通过id查询")
    @ApiOperation(value = "终端组织机构-通过id查询", notes = "终端组织机构-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
		SysDepart momgDept = sysDepartService.getById(id);
        if (momgDept == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(momgDept);
    }

	@GetMapping(value = "/queryRoomByDepartId")
	public Result<?> queryRoomByDepartId(@RequestParam(name = "departId", required = true) String departId) {
		List<SysDepartRoom> sysDepartRooms = sysDepartRoomService.list(new QueryWrapper<SysDepartRoom>().eq("depart_id", departId));

		String[] roomIds = sysDepartRooms.stream().map(SysDepartRoom::getRoomId).toArray(String[]::new);
		return Result.OK(roomIds);

	}

}
